{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}
<form class="layui-form p-4">
    <h3 class="pb-3">物料领用单</h3>
    <table class="layui-table layui-table-form">
        <tr>
            <td class="layui-td-gray">物品名称<font>*</font>
            </td>
            <td colspan="3">
                <input type="text" name="name" value="" placeholder="请输入物品名称检索" class="layui-input">
            </td>
            <td>
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="searchName"><i
                        class="layui-icon layui-icon-search mr-1"></i>搜索</button>
    
                <button type="reset" class="layui-btn layui-btn-reset" lay-filter="reset">清空</button>
    
            </td>
        </tr>
    </table>
</form>

<form class="layui-form p-4">

    <table class="layui-goods" id="ID-table-demo-templet"></table>


    <table class="layui-table layui-table-form">
        <td class="layui-td-gray">领料合计
        </td>
        <td class="goddsNumber">
            0
        </td>
        <td class="layui-td-gray">领料金额
        </td>
        <td class="goodsPrice">
            0
        </td>

        {if condition="$eid gt 0"}
        <input type="hidden" name="eid" value="{$eid}" lay-verify="required">
        {else/}
        <tr>
            <td class="layui-td-gray">所在企业<font>*</font>
            </td>
            <td colspan="3">
                <select name="eid" lay-verify="required" lay-reqText="请选择所属企业" lay-filter="asyncEidSelect"
                    id="async-eid-select">
                    <option value="0">系统管理员</option>
                    {volist name="enterprise" id="v"}
                    <option value="{$v.id}" {notempty name="$detail.eid" } {eq name="$v.id" value="$detail.eid" }
                        selected{/eq}{/notempty}>{$v.title}</option>
                    {/volist}
                </select>
            </td>
        </tr>
        {/if}
        <td class="layui-td-gray">选择员工<font>*</font>
        <td>
            <select name="uid" lay-verify="required" lay-reqText="请选择员工" lay-filter="asyncUserSelect"
                id="async-User-select">

            </select>
        </td>
        <td class="layui-td-gray">选择项目<font>*</font>
        <td>
            <select name="item_id" lay-verify="required" lay-reqText="请选择项目" lay-filter="asyncItemSelect"
                id="async-item-select">

            </select>
        </td>
        </td>

        </tr>
        <tr>
            <td class="layui-td-gray">出库时间<font>*</font>
            <td>
                <!-- <input type="text" id="out_time_data" lay-verify="out_time" placeholder="请选择出库时间" class="layui-input"> -->
                <input type="text" name="out_time" class="layui-input" id="ID-laydate-demo" placeholder="请选择出库时间">
            </td>
            <td class="layui-td-gray">出库编号<font>*</font>
            <td>
                <input type="text" name="out_code" lay-verify="required" {notempty name="$detail.out_code"
                    }value="{$detail.out_code}" {/notempty} lay-reqText="请输入出库编号" autocomplete="off"
                    placeholder="请输入出库编号" class="layui-input">
            </td>
        </tr>
    </table>
    <div class="py-3">
        <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="webform">立即提交</button>
        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
</form>
<script type="text/html" id="flow-template">
    {{#  layui.each(d.data, function(index, item){ }}
      <option value="{{ item.value }}">{{ item.text }}</option>
    {{#  }); }}

 


  </script>
{/block}
<!-- /主体 -->

<!-- 脚本 -->
{block name="script"}

<script>
    const moduleInit = ['tool', 'employeepicker'];
    // 正整数正则表达式
    const regex = /^[1-9]\d*$/;

    // 测试函数
    function isPositiveInteger(value) {
        return regex.test(value);
    }
    function gouguInit() {
        var form = layui.form, tool = layui.tool, table = layui.table, employeepicker = layui.employeepicker, laydate = layui.laydate;
        // 根据返回数据中某个字段来判断开启该行的编辑
        var editable = function (d) {

            if (d.LAY_CHECKED) return true; // 这里假设以 editable 字段为判断依据
        };
        var flow = layui.flow;
        var eid = '{$eid}';
        var name = '';
        form.on('select(asyncEidSelect)', function (data) {
            eid = data.value;
            table.reload('ID-table-demo-templet', {
                where: {
                    eid
                }
            });
        });
        // 日期
        laydate.render({
            elem: '#ID-laydate-demo'
        });
        // 搜索提交
        form.on('submit(searchName)', function (data) {

            var field = data.field; // 获得表单字段
            console.log(data)
            // 执行搜索重载
            table.reload('ID-table-demo-templet', {
                page: {
                    curr: 1 // 重新从第 1 页开始
                },
                where: {
                    eid,
                    ...field
                } // 搜索的字段
            });
            return false; // 阻止默认 form 跳转
        });



        table.render({
            elem: '#ID-table-demo-templet',
            id: 'ID-table-demo-templet',
            url: '/home/goodsCollar/getPageGoods', // 此处为静态模拟数据，实际使用时需换成真实接口
            page: true,
            height: '315px',
            where: {
                eid,
                name,
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                // 未自定义模板的普通列
                { field: 'id', fixed: 'left', width: 80, title: 'ID', sort: true },
                // 模板 - 选择器写法
                { field: 'code', title: '材料编码', },
                { field: 'name', title: '材料名称', },
                { field: 'version', title: '规格型号', },
                { field: 'unit', title: '计量单位', },
                { field: 'price', title: '单价', },
                { field: 'num', title: '库存数量', },
                { field: 'all_price', title: '金额', },
                { field: 'addnum', title: '领用数量', edit: editable },


            ]]
        });
        table.on('edit(ID-table-demo-templet)', function (obj) {
            var value = obj.value;
            var data = obj.data // 得到所在行所有键值
            // 值的校验
            if (value.replace(/\s/g, '') === '') {
                layer.tips('值不能为空', this, { tips: 1 });
                return obj.reedit(); // 重新编辑 -- v2.8.0 新增
            }
            if (!isPositiveInteger(value)) {
                layer.tips('输入正整数', this, { tips: 1 });
                return obj.reedit(); // 重新编辑 -- v2.8.0 新增
            }


            if (value > data.num) {
                layer.tips('领用数量大于可领用数', this, { tips: 1 });
                obj.update(data, true)
                return obj.reedit(); // 重新编辑 -- v2.8.0 新增
            }

            setTotalRowNum();

        });
        table.on('checkbox(ID-table-demo-templet)', function (obj) {
            var isChecked = obj.checked;
            var index = obj.index;
            var data = table.cache['ID-table-demo-templet'];
            if (obj.type == 'all') {
                var AllData = table.getData('ID-table-demo-templet');
                if (isChecked) {
                    data.map(e => {
                        e.addnum = e.num;
                    })
                    console.log(AllData, '1111')

                } else {
                    data.map(e => {
                        e.addnum = 0;
                    })
                }
                console.log(AllData, '1111')

            } else {
                if (!isChecked) {
                    data[index]['addnum'] = 0;

                } else {
                    data[index]['addnum'] = data[index]['num'];
                }
            }
            setTotalRowNum();
            table.renderData('ID-table-demo-templet')

        });


        form.on('select(asyncEidSelect)', function (data) {
            table.reload('ID-table-demo-templet', { where: { eid: data.value } })
            getPageUser(data.value);
            getPageItemData(data.value);

        });

        //初始化User->Item
        getPageUser('{$eid}');
        getPageItemData('{$eid}');

        //获取项目
        function getPageItemData(eid) {
            $.getJSON('/home/goodsCollar/getPageItem?eid=' + eid, function (res) {


                var html = '';
                layui.each(res.data, function (index, item) {
                    html += '<option value="' + item.id + '">' + item.name + '</option>';
                });
                document.getElementById('async-item-select').innerHTML = html;
                form.render($('#async-item-select')); // 重新渲染select
                // 模拟数据输出

                console.log(res); // 被选中的值
            });
        };
        //获取人员
        function getPageUser(eid) {
            $.getJSON('/home/goodsCollar/getPageUser?eid=' + eid, function (res) {
                var html = '';
                layui.each(res.data, function (index, item) {
                    html += '<option value="' + item.id + '">' + item.name + '</option>';
                });
                document.getElementById('async-User-select').innerHTML = html;
                form.render($('#async-User-select')); // 重新渲染select
                // 模拟数据输出

                console.log(res); // 被选中的值
            });
        }

        function setTotalRowNum() {
            let checkStatus = table.checkStatus('ID-table-demo-templet')['data'];
            let goddsNumber = $('.goddsNumber');
            let goodsPrice = $('.goodsPrice');
            if (checkStatus.length == 0) {
                goddsNumber.html(0); //统计领用总数量
                goodsPrice.html(0); //统计领用总金额
            } else {

                let num = checkStatus.reduce((prev, cur) => {
                    return prev * 1 + cur.addnum * 1;
                }, 0)
                let pic = checkStatus.reduce((prev, cur) => {
                    return prev * 1 + cur.addnum * cur.price;
                }, 0)
                goddsNumber.html(num); //统计领用总数量
                goodsPrice.html(pic); //统计领用总金额
            }





            console.log(checkStatus)
            console.log(goddsNumber)
        }






        //监听提交
        form.on('submit(webform)', function (data) {
            let goods = [];
            let checkStatus = table.checkStatus('ID-table-demo-templet')['data'];

            checkStatus.forEach(e => {
                goods.push({
                    good_id: e.id,
                    name: e.name,
                    num: e.addnum,
                    price: e.price
                })
            })
            data.field.goods = goods;
            data.field.num = $('.goddsNumber').html();
            data.field.money = $('.goodsPrice').html();

            let callback = function (e) {
                layer.msg(e.msg);
                if (e.code == 0) {
                    tool.sideClose(1000);
                }
            }

            tool.post("/home/goodsCollar/add", data.field, callback);
            return false;

        });

        var form = layui.form,
            tool = layui.tool,
            oaTool = layui.oaTool,
            laydate = layui.laydate;
        //日期时间范围
        laydate.render({
            elem: '#start_time',
            type: 'date',
            format: 'yyyy-MM-dd',
            showBottom: false
        });
        //日期时间范围
        laydate.render({
            elem: '#end_time',
            type: 'date',
            format: 'yyyy-MM-dd',
            showBottom: false
        });

    }
</script>
{/block}
<!-- /脚本 -->